import axios from 'axios'
import store from "../store"
import Router from '../router'
// import {
//   baseURL
// } from '@/config'
// import Router from '@/router'
let baseURL = ""
class HttpRequest {
  constructor(baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
  }
  getInsideConfig() {
    const config = {
      baseURL: this.baseUrl,
      params: {}
    }
    return config
  }
  distroy(url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) { }
  }
  interceptors(instance, url) {
    instance.interceptors.request.use(config => {
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {

      }
      return config
    }, error => {
      // Message.error('请求超时!')
      return Promise.reject(error)
    })
    instance.interceptors.response.use(res => {
      this.distroy(url)
      const {
        data
      } = res 
      if(res.data.code==200){
        const {
          data
        } = res 
        return data;
      }
      if (res.data.code === 401) {
        console.log("401")
        // 401 说明 token 验证失败
        // 可以直接跳转到登录页面，重新登录获取 token
       // localStorage.removeItem('access_token')
        store.commit("updateAccessToken",'')
        Router.push({
          path: '/login'
        })
      } else if (res.data.code === 500) {
        // 服务器错误
        // do something
        console.log("系统异常")
        return res
      } else {
        //返回 response 里的错误信息
        this.distroy(url)
        return Promise.reject(res)
      }

      return data
    }, error => {
      console.log("error",error)
        //返回 response 里的错误信息
        this.distroy(url)
        return Promise.reject(error.response.data)
      
    })
  }
  request(options) {
    let access_token = store.state.accessToken;
    const instance = axios.create()
    if (access_token) {
      options = Object.assign(this.getInsideConfig(), {
        headers: {
          'Content-Type': 'application/json',
          "accessToken": access_token
        }
      }, options)
    } else {
      options = Object.assign(this.getInsideConfig(), options)
    }

    this.interceptors(instance, options.url)
    return instance(options)
  }
}
export default HttpRequest
